<script setup lang="ts">
import { onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import _ from 'lodash';
import { getCategoryGet } from '@/services/goodsCategory.ts';
import type { GoodsCategoryList } from '@/types/goodsCategory.ts';

const $router = useRouter();
const goodsCategoryList = ref<GoodsCategoryList[]>([]);
const categoryData = reactive({
  active: 0,
});

// 弹窗
const carPop = ref(false);
const joinCarData = ref({});
const onJoinCarClick = (props: any) => {
  carPop.value = true;
  joinCarData.value = props;
};
const onImageClick = (props: any) => {
  console.log('props', props);
  $router.push({
    path: `/goodsDetails/${props.goodsId}`,
  });
};

const loadData = async () => {
  try {
    // 获取所有的分类信息
    const { data, err } = await getCategoryGet();
    if (err) {
      showToast(err);
      return;
    }
    goodsCategoryList.value = data.catList;
  } catch (error: any) {
    showToast(error);
  }
};
const onSidebarItemClick = (index: number) => {
  window.removeEventListener('scroll', scollNav, true);
  categoryData.active = index;
  let navPage = document.querySelector('#scroll' + index) as HTMLElement;
  let parent = document.querySelector('#goodListId') as HTMLElement;
  if (!navPage || !parent) {
    return;
  }
  // 计算滚动位置 offsetTop:获取当前元素相对于其最近的已定位祖先元素的顶部内边距的距离
  const targetPosition = (navPage.offsetTop ?? 0) - (parent.offsetTop ?? 0);
  parent.scrollTo({
    top: targetPosition,
    // behavior: 'smooth', // 关键参数：启用平滑滚动; 监听了滚动事件，所以不能启用
  });
  // 点击后会触发滚动事件，所以要延迟执行
  setTimeout(() => {
    window.addEventListener('scroll', scollNav, true);
  }, 100);
};
const scollNav = _.debounce(() => {
  let parent = document.querySelector('#goodListId') as HTMLElement;
  for (let i = 0; i < goodsCategoryList.value.length; i++) {
    let navPage = document.querySelector('#scroll' + i) as HTMLElement;
    if (navPage?.offsetTop <= parent.scrollTop + 20) {
      categoryData.active = i;
    }
  }
}, 300);

onMounted(() => {
  window.addEventListener('scroll', scollNav, true);
  loadData();
});
onUnmounted(() => {
  window.removeEventListener('scroll', scollNav, true);
});
</script>

<template>
  <div class="container">
    <van-sidebar v-model="categoryData.active">
      <van-sidebar-item
        @click="onSidebarItemClick(index)"
        v-for="(category, index) in goodsCategoryList"
        :key="category.catId"
        :title="category.catName"
      />
    </van-sidebar>
    <div class="content" id="goodListId">
      <div
        class="category-box"
        v-for="(goods, index) in goodsCategoryList"
        :key="goods.catId"
        :id="'scroll' + index"
      >
        <div class="box-title">{{ goods.catName }}</div>
        <div class="goods-box" v-for="item in goods.goodsList" :key="item.goodsId">
          <div class="box-left">
            <van-image @click="onImageClick(item)" :src="item.goodsImg?.split(',')[0]" />
          </div>
          <div class="box-right">
            <div class="right-text">
              <van-text-ellipsis rows="2" :content="item.goodsName" />
            </div>
            <div class="right-bottom">
              <div class="price-text">
                <span class="right-price">￥</span>
                <span>{{ item.goodsSalesPrice }}</span>
              </div>
              <svg-icon @click="onJoinCarClick(item)" icon-class="car" size="1.5em" />
            </div>
          </div>
        </div>
      </div>
      <div class="no-more">暂无更多~</div>
    </div>
  </div>
  <JoinCar v-model="carPop" :joinCarData="joinCarData"></JoinCar>
</template>

<style lang="scss" scoped>
.container {
  display: flex;
  height: calc(100vh - 50px); /* 确保容器有固定高度 */
  overflow: hidden;

  .content {
    width: 100%;
    position: relative;
    overflow: auto;
  }

  .category-box {
    width: 100%;
    padding-left: 4px;
    margin-bottom: 12px;

    .box-title {
      height: 50px;
      line-height: 50px;
      color: #222222;
      font-size: 14px;
      font-weight: 500;
    }

    .goods-box {
      width: 100%;
      height: 88px;
      padding-left: 4px;
      margin-bottom: 12px;
      display: flex;

      .box-left {
        width: 80px;
        height: 100%;

        .van-image {
          width: 80px;
          height: 100%;
        }
      }

      .box-right {
        width: 100%;
        height: 100%;
        padding: 4px 0 4px 4px;
        display: flex;
        flex-direction: column;
        justify-content: space-between;

        .right-text {
          font-size: 13px;
          font-weight: 500;
          color: #000000;
        }

        .right-bottom {
          font-size: 14px;
          font-weight: 500;
          color: #e86600;
          height: 22px;
          padding-right: 16px;
          display: flex;
          align-items: center;
          justify-content: space-between;

          .price-text {
            .right-price {
              font-size: 10px;
              font-weight: 400;
            }
          }
        }
      }
    }
  }

  .no-more {
    width: 100%;
    height: 20px;
    margin: 20px 0;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    color: #999999;
  }

  :deep(.van-sidebar) {
    position: relative;
    min-width: 88px !important;
    max-width: 88px !important;
    height: 100% !important;

    &::before {
      position: absolute;
      top: 50%;
      left: initial;
      right: 0;
      width: 1px;
      height: 100%;
      background-color: #ebebeb;
      transform: translateY(-50%);
      content: '';
    }
  }

  .van-sidebar-item {
    height: 60px;
    background: #fff;

    &::before {
      position: absolute;
      top: 50%;
      left: initial;
      right: 0;
      width: 1px;
      height: 100%;
      background-color: #ebebeb;
      transform: translateY(-50%);
      content: '';
    }
  }

  .van-sidebar-item--select {
    color: #00ba9f;

    &::before {
      position: absolute;
      width: 1.5px;
      height: 100%;
      top: 50%;
      right: 0;
      left: initial;
      background-color: #00ba9f;
      transform: translateY(-50%);
      content: '';
    }
  }
}
</style>
